import util from '../../utils/util';
var qcloud = require('../../vendor/sdk/index');
var config = require('../../config');
const app = getApp();

//居中展示当前选中的分类
//参考博客：https://www.cnblogs.com/chanwahfung/archive/2020/03/24/12563035.html

Page({
  data: {
    navH: app.globalData.navHeight,
    application: config.application,
    theme: config.theme,
    hotProgramList: [],
    categoryList: [],
    guideWechatList: [],
    subscribeProgramList: [],
    fileHost: app.globalData.imageUrl,
    showStatus: 'hot',
    lastProgramId: '',
    hotPageSize: 2,
    hotPageNum: 1,
    subscribePageSize: 10,
    subscribePageNum: 1,
    isMore: false,
    loading: false,
    previousChatRoomProgram: null,
    iteractionWechat: {id: 9999, wechatName: "线上互动", showText: "更多", appId: "wx6bc98c30de344937"},
    // iteractionWechat: {id: 9999, wechatName: "网上互动", showText: "更多", appId: "wxa2a78071ac5db945"}
  },
  onLoad(option) {
    console.log('index.js onLoad', option);
    // option.notice="1";
    // option.programId="1";
    // option.messageId="57";
    if (!app.globalData.userInfo) {
      console.log('没有用户信息');
      // 登录
      app.getUserInfo().then(userInfo => {
        console.log('获取用户信息', userInfo);
        this.recentProgramRedirect(option, userInfo);
      });
    } else {
      this.recentProgramRedirect(option);
    }
    
    if (option && option.previousChatRoomProgram) {
      console.log(decodeURIComponent(decodeURIComponent(option.previousChatRoomProgram)));
      try {
        let previousChatRoomProgram = JSON.parse(decodeURIComponent(decodeURIComponent(option.previousChatRoomProgram)));
        // 将要置顶的互动放置到数组开头
        let hotProgramList = this.data.hotProgramList;
        if (previousChatRoomProgram.visit == 1 && previousChatRoomProgram.auditStatus == 2) {
          hotProgramList.unshift(previousChatRoomProgram)
        }
        this.setData({
          previousChatRoomProgram: previousChatRoomProgram,
          hotProgramList: hotProgramList,
          scrollLeft: option.scrollLeft
        }, () => {
          this.getCategoryList();
        });
      } catch (error) {
        console.log('error-------------', error);
        this.getCategoryList();
      }
    } else {
      this.getCategoryList();
    }
  },
  onReady(){
    wx.createSelectorQuery().select('.scroll-view_H').boundingClientRect((rect)=>{
      this.data.scrollViewWidth = Math.round(rect.width);
    }).exec();
  },  
  onPullDownRefresh() {
    // 整个页面下拉重新加载数据
    this.setData({
      hotPageNum: 1,
      hotProgramList: [],
      subscribePageNum: 1,
      subscribeProgramList: []
    }, () => {
      if (this.data.showStatus === 'hot') {
        let params = { categoryId: this.data.effectiveCategory.id }
        this.getHotProgramList(params);
      } else if (this.data.showStatus === 'subscribe') {
        this.getSubscribeProgramList();
      }
      // 拉取分类
      this.getCategoryList();
      setTimeout(() => wx.stopPullDownRefresh(), 500);
    });
  },
  onReachBottom() {
    // 触底加载新数据
    if (this.data.showStatus === 'hot') {
      let params = { categoryId: this.data.effectiveCategory.id }
      this.getHotProgramList(params);
    } else if (this.data.showStatus === 'subscribe') {
      this.getSubscribeProgramList();
    }
  },
  onShow() {
    console.log('index.js onShow');
    // 判断缓存中是否有未持久化的语音消息id
    util.syncReadedVoiceMessage();
  },
  navigateToMiniProgram(e) {
    let self = this;
    let wechat = e.currentTarget.dataset.wechat;
    console.log('wechat', wechat);
    self.setData({
      effectiveWechat: wechat,
      effectiveCategory: null,
    }, () => {
      util.miniProgramClickCountIncrease(wechat.id);
      wx.navigateToMiniProgram({
        appId: wechat.appId,
        path: '/pages/index/index',
        success(res) {
          // 打开成功
          console.log('跳转成功success', res);
        }
      });
    });
  },
  recentProgramRedirect(option, userInfo) {
    console.log('index recentProgramRedirect option', option);
    console.log('index recentProgramRedirect userInfo', userInfo);
    // 服务通知跳转情况处理
    if (option && option.notice && option.notice == 1 && option.messageId) {
      console.log('服务通知跳转情况处理-@');
      let programId = option.programId;
      let messageId = option.messageId;
      let url = `/pages/chat/chat?programId=${programId}&messageId=${messageId}`;
      console.log('index notice url', url);
      wx.redirectTo({
        url: url
      });
    } else {
      // 最后浏览栏目情况处理
      if (userInfo && userInfo.role !== -1 && userInfo.lastVisitPage && userInfo.lastVisitPage != null && userInfo.lastVisitPage != 'null') {
        console.log('跳转到最后一次浏览的互动页');
        this.redirectToLastProgram(userInfo);
      }
    }
  },
  redirectToLastProgram(userInfo) {
    let programId = 0;
    if (userInfo.lastVisitPage) {
      let arr = userInfo.lastVisitPage.split('=');
      programId = arr[1];
    }
    // 获取互动信息
    qcloud.request({
      url: config.service.getProgramInfoUrl,
      data: {
        id: programId
      },
      success: res => {
        console.log('getProgramById-res', res);
        let program = res.data.data;
        if (program) {
          wx.redirectTo({
            url: userInfo.lastVisitPage
          });
        }
      }
    });
  },
  getCategoryList() {
    let self = this;
    qcloud.request({
      url: config.service.getCategoryListUrl,
      data: {},
      success: res => {
        let showIndex = 0;
        let scrollLeft = 0;
        let categoryList = res.data.data && res.data.data.categories;
        let guideWechatList = res.data.data && res.data.data.guideWechats;
        if (categoryList && categoryList.length > 0) {
          // 是否有置顶节目
          let previousChatRoomProgram = self.data.previousChatRoomProgram;
          let topCategory = null;
          if (previousChatRoomProgram != null) {
            
            categoryList.forEach((item, index) => {
              if (item.id === previousChatRoomProgram.categoryId) {
                showIndex = index;
                topCategory = item;
              }
            });
            scrollLeft = self.data.option && self.data.option.scrollLeft;
            //当前置顶节目所属分类，在第二阵营置顶
            if (topCategory != null) {
              categoryList = categoryList.filter(item => topCategory.id !== item.id);
              categoryList.unshift(topCategory);
              showIndex = 0;
            }
          } else if (this.data.option && this.data.option.effectiveId) {
            categoryList.map(item => {
              if (item.id == this.data.option.effectiveId) {
                topCategory = item;
              }
            });
            if (topCategory) {
              categoryList = categoryList.filter(item => topCategory.id !== item.id);
              categoryList.unshift(topCategory);
              showIndex = 0;
            }
          }
        }

        let application = this.data.application;
        if (application === 6 || application === 7 || application === 8 || application === 9 || application === 5 || application === 2 || application === 3 || application === 4 || application === 10) {
          categoryList.push(this.data.iteractionWechat);
        }
        self.setData({
          categoryList: categoryList,
          guideWechatList: guideWechatList,
          effectiveCategory: categoryList && categoryList.length>0 && categoryList[showIndex],
        }, () => {
          self.getHotProgramList({ categoryId: categoryList[showIndex].id});
        });
      }
    });
  },
  categoryChange(e) {
    let self = this;
    let category = e.currentTarget.dataset.category;
    console.log('category', category);
    //计算滚动距离
    let offsetLeft = e.currentTarget.offsetLeft
    self.setData({
      scrollLeft: (offsetLeft - this.data.scrollViewWidth/2) + 16
    });
    console.log("scrollLeft------>", this.data.scrollLeft);
    if (!this.data.effectiveCategory || this.data.effectiveCategory.id != category.id) {
      self.setData({
        hotProgramList: [],
        hotPageNum: 1,
        hotPageSize: 10,
        effectiveCategory: category,
        effectiveWechat: null
      }, () => {
        let params = { categoryId: category.id };
        util.categoryClickCountIncrease(category.id);
        self.getHotProgramList(params);
      });
    }
  },
  getHotProgramList(params) {
    // 获取热门互动列表
    let { hotPageNum, hotPageSize, hotProgramList } = this.data;
    wx.showLoading({
      title: '加载中...'
    });
    qcloud.request({
      url: config.service.getHotProgramListUrl,
      data: {
        pageNum: hotPageNum,
        pageSize: hotPageSize,
        visit: 1,
        ...params
      },
      success: res => {
        wx.hideLoading();
        let hotPageList = res.data.data;
        if (hotPageList && hotPageList.length > 0) {
          hotPageList.forEach(v => {
            v.startTime = v.startTime && v.startTime.substr(0, 5);
            v.endTime = v.endTime && v.endTime.substr(0, 5);
          });
          // 过滤需要置顶的互动
          if (this.data.previousChatRoomProgram != null) {
            hotPageList = hotPageList.filter(item => item.id != this.data.previousChatRoomProgram.id);
          }
          this.setData({
            hotPageNum: hotPageNum + 1,
            hotProgramList: this.data.hotProgramList.concat(hotPageList),
            previousChatRoomProgram: null,
            option: null
          });
        }
      },
      fail: err => {
        wx.hideLoading();
      }
    });
  },
  getSubscribeProgramList() {
    if (app.globalData.userInfo.role == -1) {
      this.setData({
        subscribeProgramList: []
      });
      return;
    }
    // 获取订阅互动
    let {
      subscribePageNum,
      subscribePageSize,
      subscribeProgramList
    } = this.data;
    wx.showLoading({
      title: '加载中'
    });
    qcloud.request({
      url: config.service.getSubscribeProgramListUrl,
      data: {
        userId: app.globalData.userInfo.id,
        pageNum: subscribePageNum,
        pageSize: subscribePageSize
      },
      success: res => {
        wx.hideLoading();
        let subscribePageList = res.data.data;
        if (subscribePageList && subscribePageList.length > 0) {
          subscribePageList.forEach(v => {
            v.startTime = v.startTime && v.startTime.substr(0, 5);
            v.endTime = v.endTime && v.endTime.substr(0, 5);
          });
          this.setData({
            subscribePageNum: subscribePageNum + 1,
            subscribeProgramList: subscribeProgramList.concat(subscribePageList)
          });
        }
      },
      fail: err => {
        wx.hideLoading();
      }
    });
  },
  changePanel(e) {
    // 面板切换
    this.setData({
      hotPageNum: 1,
      hotProgramList: [],
      subscribePageNum: 1,
      subscribeProgramList: [],
      showStatus: e.target.dataset.status
    }, () => {
      if (this.data.showStatus === 'hot') {
        let params = { categoryId: this.data.effectiveCategory.id }
        this.getHotProgramList(params);
      } else if (this.data.showStatus === 'subscribe') {
        this.getSubscribeProgramList();
      }
    }
    );
  },
  goPersonalPage() {
    //effectiveCategory
    // 导航个人中心
    wx.redirectTo({
      url: `/pages/personalPage/personalPage?effectiveId=${this.data.effectiveCategory.id}`
    });
  },
  gochat(e) {
    console.log('gochat scrollLeft', this.data.scrollLeft);
    // 进入聊天室
    if (!app.globalData.userInfo) {
      app.getUserInfo().then(userInfo => {
        this.setData({
          userInfo,
          loading: false
        });
        let program = e.currentTarget.dataset.program;
        wx.redirectTo({
          url: '/pages/chat/chat?programId=' + program.id
        });
      });
    } else {
      let program = e.currentTarget.dataset.program;
      wx.redirectTo({
        url: `/pages/chat/chat?programId=${program.id}&scrollLeft=${this.data.scrollLeft}`
      });
    }
  },
  onShareAppMessage() {
    // 分享
    return {
      title: `${this.data.theme.indexShareTitle}`
    };
  },
  scanCode() {
    // 扫码进入聊天室
    wx.scanCode({
      onlyFromCamera: false,
      // scanType: ['qrCode'], // 使用scanCode扫码时指定qrCode,便只能识别二维码不能识别小程序码, 暂时注释掉
      success: res => {
        console.log('code-url=', res);
        wx.redirectTo({
          url: '/' + res.path
        });
      }
    });
  },
  cancelSubscribe(e) {
    // 取消订阅
    let self = this;
    wx.showModal({
      content: '确认不再关注？',
      confirmText: '确定',
      cancelText: '取消',
      success: function (res) {
        if (res.confirm) {
          let program = e.currentTarget.dataset.program;
          qcloud.request({
            url: config.service.cancelSubscribeProgramUrl,
            data: {
              userId: app.globalData.userInfo.id,
              programId: program.id
            },
            success: res => {
              wx.showToast({
                title: '取消成功',
                icon: 'success',
                duration: 2000
              });
              console.log(
                'cancel before subscribePageNum=',
                self.data.subscribePageNum
              );
              app.refreshUserInfo();
              self.setData({
                subscribePageNum: 1,
                subscribeProgramList: [],
                previousChatRoomProgram: null,
              }, () => {
                console.log(
                  'cancel after subscribePageNum=',
                  self.data.subscribePageNum
                );
                self.getSubscribeProgramList();
              }
              );
            }
          });
        }
      }
    });
  }
});
